package com.android.base.okhttp.okUtil;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;

import com.android.base.okhttp.RxHttpClient;
import com.android.base.tools.EmptyUtil;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import java.net.URLEncoder;
import java.util.*;

/**
 * Created by Sammie on 2017/9/8.
 * 基于OKHttp的简单封装。
 * 构建地址，创建Client. 其他参数构建详见MethodBuild
 */
public class OKHttpUtil {

    private OkHttpClient client;
    private Request.Builder requestBuilder;
    private Context mContext;

    public OKHttpUtil(Context context) {
        //获取Client
        client = new RxHttpClient(context).getClient();
        requestBuilder = new Request.Builder();
        this.mContext = context;
    }

    /**
     * 对OKHttpUtil进行基本设置
     *
     * @param config
     */
    public OKHttpUtil(Context context, RxClientBuilder config) {
        //获取Client
        client = new RxHttpClient(context, config).getClient();
        requestBuilder = new Request.Builder();
        if (config.isCommonHead()) {
            //TODO 公共head,可以统一添加
            requestBuilder.addHeader("token", "");
        }
    }

    public ParamsBuild url(String httpUrl) {
        if (EmptyUtil.check(httpUrl) && EmptyUtil.check(httpUrl)) {
            throw new NullPointerException("地址：url == null");
        }
        requestBuilder.url(httpUrl);
        requestBuilder.addHeader("SOURCE","2");
//        requestBuilder.addHeader("IDFA",getDeviceId());
        requestBuilder.addHeader("APP_NAME", "meng_xiang");
        return new ParamsBuild(mContext, requestBuilder, client);
    }

    public ParamsBuild url(HttpUrl _httpUrl) {
        if (EmptyUtil.check(_httpUrl) && EmptyUtil.check(_httpUrl)) {
            throw new NullPointerException("地址：url == null");
        }
        requestBuilder.url(_httpUrl);
        requestBuilder.addHeader("SOURCE","2");
//        requestBuilder.addHeader("IDFA",getDeviceId());
        requestBuilder.addHeader("APP_NAME","meng_xiang");
        return new ParamsBuild(mContext, requestBuilder, client);
    }

    public ParamsBuild urlByHeadData(String httpUrl, Map<String, String> headMap) {
        if (EmptyUtil.check(httpUrl) && EmptyUtil.check(httpUrl)) {
            throw new NullPointerException("地址：url == null");
        }
        requestBuilder.url(httpUrl);
        if (headMap != null && headMap.size() != 0) {
            Iterator iter = headMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String,String> entry = (Map.Entry) iter.next();
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        requestBuilder.addHeader("SOURCE","2");
//        requestBuilder.addHeader("IDFA",getDeviceId());
        requestBuilder.addHeader("APP_NAME","meng_xiang");
        return new ParamsBuild(mContext, requestBuilder, client);
    }

    public ParamsBuild urlByHeadData(String httpUrl,Map<String, String> params, Map<String, String> headMap) {
        if (EmptyUtil.check(httpUrl) && EmptyUtil.check(httpUrl)) {
            throw new NullPointerException("地址：url == null");
        }
        requestBuilder.url(httpUrl + "?" + createLinkStringByGet(params));
        if (headMap != null && headMap.size() != 0) {
            Iterator iter = headMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String,String> entry = (Map.Entry) iter.next();
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        requestBuilder.addHeader("SOURCE","2");
//        requestBuilder.addHeader("IDFA",getDeviceId());
        requestBuilder.addHeader("APP_NAME","meng_xiang");
        return new ParamsBuild(mContext, requestBuilder, client);
    }

    public ParamsBuild url(String httpUrl, Map<String, String> params) {
        if (EmptyUtil.check(httpUrl) && EmptyUtil.check(httpUrl)) {
            throw new NullPointerException("地址：url == null");
        }
        requestBuilder.url(httpUrl + "?" + createLinkStringByGet(params));
        requestBuilder.addHeader("SOURCE","2");
//        requestBuilder.addHeader("IDFA",getDeviceId());
        requestBuilder.addHeader("APP_NAME","meng_xiang");
        return new ParamsBuild(mContext, requestBuilder, client);
    }


    /**
     * 　　* 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * 　　* @param params 需要排序并参与字符拼接的参数组
     * 　　* @return 拼接后字符串
     * 　　* @throws UnsupportedEncodingException
     */
    private String createLinkStringByGet(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";

        for (int i = 0; i <= keys.size(); i++) {
            if (i == keys.size()){
                prestr += "app_name=meng_xiang";
                break;
            }
            String key = keys.get(i);
            String value = params.get(key);
            try {
                value = URLEncoder.encode(value, "UTF-8");
            } catch (Exception e) {
            }
            prestr = prestr + key + "=" + value + "&";
        }

        return prestr;
    }
}
